#include "submodule.h"

#define MIN_VAL 0
#define MAX_VAL 500

SubModule::SubModule(QObject *parent) :
    QObject(parent)
{

    nam = new QNetworkAccessManager;
    nam->setParent(this);


    for (int c = MIN_VAL; c != MAX_VAL; c++)
    {
        nam->get(QNetworkRequest(QUrl("http://eu.battle.net/api/wow/item/" + QString::number(c))));
    }

    QObject::connect(this, &SubModule::finishedIs,
                     [=](int fl)
    {
        if ( fl == MAX_VAL-1)
        {
            QFile file("map.txt");
            if (!file.open(QIODevice::Append | QIODevice::Text))
                file.errorString();
            file.write(QVariant(str).toByteArray());
            file.close();
            //qDebug()<<str;
        }

    });
    QObject::connect(nam, &QNetworkAccessManager::finished,
                     [=] (QNetworkReply* reply)
    {
        fl++;
        if (reply->error() == QNetworkReply::NoError)
        {
            QJsonParseError  parseError;
            QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &parseError);

            if(parseError.error == QJsonParseError::NoError)
            {
                qDebug()<<fl;
                str.append(jsonDoc.object().take("id").toVariant().toString());
                str.append("  =  ");
                str.append(jsonDoc.object().take("icon").toVariant().toByteArray());
                str.append("\n");
                finishedIs(fl);
            }
            else
            {
                qDebug()<<parseError.errorString();
            }
        }
        else
        {
            qDebug()<<reply->errorString();
        }
        delete reply;
    });
}
